package com.wavehi.others;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author WaveHi
 * @Date 13/9/2021 下午 7:42
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description Simulate tomcat
 */
public class SimulateTomcatUp {
    //客户端
    @Test
    public void client() {
        OutputStream outputStream = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            //获取ip地址
            InetAddress inet = InetAddress.getByName("127.0.0.1");
            //获取套接字
            Socket socket = new Socket(inet, 8082);
            //获取输出流
            outputStream = socket.getOutputStream();
            //输出数据
            outputStream.write("I want to send you data.".getBytes());
            socket.shutdownOutput();
            //接收反馈
            inputStream = socket.getInputStream();
            //存储反馈的数据
            baos = new ByteArrayOutputStream();
            //接收每次读取的数据
            byte[] b = new byte[1024];
            //接收每次读取数据的长度
            int len = 0;
            //读取反馈
            while((len = inputStream.read(b)) != -1) {
                baos.write(b, 0, len);
            }
            System.out.println(baos.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源的关闭
            if(outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    //服务端
    @Test
    public void server() {
        Socket socket = null;
        try {
            //获取服务器套接字
            ServerSocket serverSocket = new ServerSocket(8082);
            //接收请求
            socket = serverSocket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //处理请求
        new Thread(new SocketHandler(socket)).start();

    }
}
